// ===================================================================
// 文件 1: main.js (已升级为 IPC 通信模式)
// ===================================================================

const { app, BrowserWindow, dialog } = require('electron');
const path = require('path');
const { fork } = require('child_process'); // 重新引入 fork

let backendProcess = null;

function createWindow() {
  const win = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      webSecurity: false,
    },
  });

  // ===================== 新增代码：捕获渲染进程崩溃事件 =====================
  // 这是定位问题的关键！
  win.webContents.on('render-process-gone', (event, details) => {
    console.error(`[Main] Renderer process crashed! Reason: ${details.reason}, Exit Code: ${details.exitCode}`);
    dialog.showErrorBox(
      '渲染进程崩溃',
      `应用的前端部分意外终止。\n\n原因: ${details.reason}\n退出代码: ${details.exitCode}\n\n请检查前端代码或依赖是否存在问题。`
    );
    // 进程崩溃后，通常也需要退出应用
    app.quit(); 
  });
  // =====================================================================

  const indexPath = path.join(__dirname, 'frontend', 'dist', 'index.html');
  win.loadFile(indexPath);
}

app.whenReady().then(() => {
  console.log('[Main] App is ready. Forking backend process...');

  const backendScriptPath = path.join(__dirname, 'backend', 'server.js');
  console.log(`[Main] Path to backend script: ${backendScriptPath}`);

  backendProcess = fork(backendScriptPath);

  backendProcess.on('message', (msg) => {
    if (msg === 'BACKEND_READY') {
      console.log('[Main] Received "BACKEND_READY" signal. Creating window...');
      createWindow();
    }
  });

  backendProcess.on('error', (err) => {
    console.error('[Main] Failed to start backend process.', err);
    dialog.showErrorBox('后端进程启动失败', `无法启动后端服务。\n\n错误: ${err.message}`);
    app.quit();
  });

  backendProcess.on('exit', (code) => {
    if (code !== 0 && backendProcess) {
      console.error(`[Main] Backend process exited unexpectedly with code ${code}`);
      dialog.showErrorBox('后端服务已停止', `后端服务意外终止。应用可能无法正常工作。`);
    }
  });
});

app.on('will-quit', () => {
  if (backendProcess) {
    console.log('[Main] App is quitting. Killing backend process...');
    backendProcess.kill();
    backendProcess = null;
  }
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});